#include <stdint.h>
#include <stdio.h>
#include <string.h>
//#include "systick.h"
#include "delay.h"
#include "lcd_drv.h"
#include "wifi_drv.h"
#include "RTT_Debug.h"
#include "wifi_app.h"
#include "hmi_common.h"
#include "FreeRTOS.h"
#include "timers.h"

extern AsciiFontDesc_t g_fontAscii30x60;
extern ChineseFontDesc_t g_fontChineseconnecting24x24;
extern ChineseFontDesc_t g_fontChineseconnectFail24x24;
extern ChineseFontDesc_t g_fontChineseconnectSucess24x24;
#define NWK_STATE_TEXT_POS_X        	50
#define NWK_STATE_TEXT_POS_Y        	150

static void DisplayNwkState()
{
	WifiConnectStatus_t nwkStatus;
	static WifiConnectStatus_t s_lastNwkStatus = WIFI_CONNECT_NWK_ING;
	LcdArea_t clearArea;
	
	clearArea.x1 = NWK_STATE_TEXT_POS_X;
	clearArea.y1 = NWK_STATE_TEXT_POS_Y;
	clearArea.x2 = LCD_PIXEL_WIDTH - 1;
	clearArea.y2 = NWK_STATE_TEXT_POS_Y + g_fontChineseconnecting24x24.height - 1;
	
	nwkStatus = GetWifiConnectStatus();
	if (s_lastNwkStatus != nwkStatus)
	{
		LcdFillPureColor(&clearArea, BLACK);
		s_lastNwkStatus = nwkStatus;
	}
	
	if (nwkStatus == WIFI_CONNECT_SERVER_FAIL)
	{
		LcdDrawChinese(NWK_STATE_TEXT_POS_X, NWK_STATE_TEXT_POS_Y, RED, BLACK, &g_fontChineseconnectFail24x24);
		return;
	}
	if (nwkStatus == WIFI_CONNECT_SERVER_SUCESS)
	{
		LcdDrawChinese(NWK_STATE_TEXT_POS_X, NWK_STATE_TEXT_POS_Y, GREEN, BLACK, &g_fontChineseconnectSucess24x24);
		return;
	}

	LcdDrawChinese(NWK_STATE_TEXT_POS_X, NWK_STATE_TEXT_POS_Y, WHITE, BLACK, &g_fontChineseconnecting24x24);
}

void DisplayNwkStatePage(void)
{
	DisplayStatusBar();
	DisplayNwkState();
}

static bool g_isCountdown;

bool IsDispCountdown()
{
	return g_isCountdown;
}

#define COUNTDOWN_TEXT_POS_X        	90
#define COUNTDOWN_TEXT_POS_Y        	150
static void DisplayNwkCfg(void)
{
	static uint64_t s_startCfgSysTime;
	char strBuf[10];
	if (!g_isCountdown)
	{
		g_isCountdown = true;
		StartSmartCfgWifi();
		s_startCfgSysTime = xTaskGetTickCount();
	}
	if (xTaskGetTickCount() - s_startCfgSysTime <= SMART_CONFIG_ENTIRE_TIMEOUT)
	{
		sprintf(strBuf, "%02d", (uint16_t)(SMART_CONFIG_ENTIRE_TIMEOUT + s_startCfgSysTime -  xTaskGetTickCount()) / 1000);
		LcdDrawString(COUNTDOWN_TEXT_POS_X, COUNTDOWN_TEXT_POS_Y, strBuf, GREEN, BLACK, &g_fontAscii30x60);
	}
	else
	{
		g_isCountdown = false;
	}
}

void DisplayNwkCfgPage(void)
{
	DisplayStatusBar();
	DisplayNwkCfg();
}
